/*!
 * \file queue.c
 * \brief Implementation for the queue class.
 * \author Vijay Ramesh
 *
 * This is a simple queue class.
 */

#include "queue.h"

void q_init ( queue_t *queue )
{
   queue->front = NULL;
   queue->back = NULL;
   queue->empty = TRUE;
   queue->size = 0;
   return;
}

int q_enqueue ( queue_t *queue, void *value )
{
   qnode_t *temp_node;
   temp_node = ( qnode_t *) malloc ( sizeof ( qnode_t ));
   if ( temp_node == NULL )
   {
      /* Out of memory */
      return 1;
   }
   else
   {
      if ( queue->empty )
      {
         /* queue is empty */
         temp_node->next = NULL;
         temp_node->value = value;
         queue->back = temp_node;
         queue->front = temp_node;
         queue->size++;
         q_set_empty ( queue );
         /* Sucess */
      }
      else
      {
         /* queue is not empty */
         queue->back->next = temp_node;
         temp_node->next = NULL;
         temp_node->value = value;
         queue->back = temp_node;
         queue->size++;
         q_set_empty ( queue );
         /* Sucess */
      }
      return 0;
   }
}

void * q_dequeue ( queue_t *queue )
{
   if ( queue->empty )
   {
      return NULL;
   }
   else
   {
      void *temp_ptr;
      temp_ptr = queue->front->value;
      qnode_t *temp_node;
      temp_node = queue->front;
      queue->front = queue->front->next;
      if ( queue->front != NULL )
      {
         queue->front->prev = NULL;
      }
      queue->size--;
      q_set_empty ( queue );
      free ( temp_node );
      return temp_ptr;
   }
}

void q_destroy ( queue_t *queue )
{
   while ( !queue->empty )
   {
      q_dequeue ( queue );
   }
   free ( queue );
   return;
}

void q_set_empty ( queue_t *queue )
{
   if ( queue->front != NULL )
   {
      queue->empty = FALSE;
   }
   else
   {
      queue->empty = TRUE;
   }
   return;
}
